/*
 * @Description: 
 * @Author: wanghongjian
 * @@github: https://github.com/whj0117
 * @Date: 2025-11-06 17:16:47
 * @LastEditors: wanghongjian
 * @LastEditTime: 2025-11-30 14:44:52
 */
import { login, logout, getInfo,commonConstants } from '@/api/user'
import { getToken, setToken, removeToken,getCompanyId,setCompanyId,removeCompanyId,setCommonConstantsStorage,getCommonConstantsStorage } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from '@/utils/md5'
import {getFormData} from '@/utils'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  realName: '',
  userId: '',
  port: '',
  message: '',
  judgeNum: '',
  count: 0,
  jumpId: '111',// 订单跟踪用到这个字段
  companyId:getCompanyId(),
  commonData:getCommonConstantsStorage()
}

const mutations = {
  SET_COMPANYID:(state,companyId) => {
    state.companyId = companyId
  },
  SET_judgeNum: (state, judgeNum) => {
    state.judgeNum = judgeNum
  },
  SET_message: (state, message) => {
    state.message = message
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_realName: (state, realName) => {
    state.realName = realName
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_Id: (state, userId) => {
    state.userId = userId
  },
  SET_Port: (state, port) => {
    state.port = port
  },
  SET_Count: (state, count) => {
    state.count = count
  },
  SET_JumpId: (state, jumpId) => {
    state.jumpId = jumpId
  },
  SET_COMMON_CONSTANTS:(state,data) => {
    state.commonData = data
  }
}

const actions = {
  setJudgeNum({ commit }, judgeNum) {
    commit('SET_judgeNum', judgeNum)
  },

  login({ commit }, userInfo) {
    const params = getFormData(userInfo)
    return new Promise((resolve, reject) => {
      login(params).then(response => {
        const { tokenValue } = response
        commit('SET_TOKEN', tokenValue)
        setToken(tokenValue)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  setCommonConstants({commit},data){
    setCommonConstantsStorage(JSON.stringify(data))
    commit('SET_COMMON_CONSTANTS', data)
  },
  setport({ commit }, port) {
    commit('SET_Port', 8087)
  },
  setcount({ commit }, count) {
    commit('SET_Count', count)
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        // const { data } = response
        // console.log(data)
        // console.log('Info',data);
        if (!data) {
          // reject('Verification failed, please Login again.')
        }
        if (data.supplierId) {
          this.$router.push('/login')
          return false
        }

        // const { roles, name, avatar, introduction } = data
        const { username: name, realName: introduction, realName: realName, userId: userId } = data
        const roles = [data.role]
        // console.log('333',introduction,realName)
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_realName', realName)
        commit('SET_Id', userId)
        // commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((res) => {
        // commit('SET_COMPANYID',null)
        commit('SET_TOKEN', '')
        // commit('SET_ROLES', [])
        // removeCompanyId()
        removeToken()
        // resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeCompanyId()
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
